<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

$db = Database::getInstance();

// 处理成就删除请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $achievementId = (int)$_GET['delete'];
    
    // 检查成就是否存在
    $achievement = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "achievements WHERE id = ?", [$achievementId]);
    
    if ($achievement) {
        // 删除与成就相关的记录
        $db->execute("DELETE FROM " . DB_PREFIX . "user_achievements WHERE achievement_id = ?", [$achievementId]);
        $db->execute("DELETE FROM " . DB_PREFIX . "achievements WHERE id = ?", [$achievementId]);
        
        // 删除成就图标（如果存在）
        if (!empty($achievement['icon']) && file_exists('../' . $achievement['icon'])) {
            @unlink('../' . $achievement['icon']);
        }
        
        $_SESSION['flash_message'] = '成就已成功删除';
        $_SESSION['flash_type'] = 'success';
    } else {
        $_SESSION['flash_message'] = '成就不存在';
        $_SESSION['flash_type'] = 'danger';
    }
    
    // 重定向以防止重复提交
    header('Location: achievements.php');
    exit;
}

// 处理成就状态修改请求
if (isset($_GET['status']) && is_numeric($_GET['achievement_id'])) {
    $achievementId = (int)$_GET['achievement_id'];
    $status = $_GET['status'] === 'active' ? 'active' : 'inactive';
    
    // 更新成就状态
    $db->update('achievements', ['status' => $status], 'id = ?', [$achievementId]);
    
    $_SESSION['flash_message'] = '成就状态已更新';
    $_SESSION['flash_type'] = 'success';
    
    // 重定向以防止重复提交
    header('Location: achievements.php');
    exit;
}

// 分页设置
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

// 搜索和筛选功能
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$gameId = isset($_GET['game_id']) ? (int)$_GET['game_id'] : 0;
$status = isset($_GET['status_filter']) ? trim($_GET['status_filter']) : '';

$searchCondition = '';
$searchParams = [];
$joinGame = false;

if (!empty($search) || $gameId > 0 || !empty($status)) {
    $conditions = [];
    
    if (!empty($search)) {
        $conditions[] = "(a.name LIKE ? OR a.description LIKE ?)";
        $searchParams[] = "%$search%";
        $searchParams[] = "%$search%";
    }
    
    if ($gameId > 0) {
        $conditions[] = "a.game_id = ?";
        $searchParams[] = $gameId;
        $joinGame = true;
    }
    
    if (!empty($status)) {
        $conditions[] = "a.status = ?";
        $searchParams[] = $status;
    }
    
    $searchCondition = " WHERE " . implode(' AND ', $conditions);
}

// 获取成就总数
$countSql = "SELECT COUNT(*) FROM " . DB_PREFIX . "achievements a";
if ($joinGame) {
    $countSql .= " JOIN " . DB_PREFIX . "games g ON a.game_id = g.id";
}
$countSql .= $searchCondition;

$totalAchievements = $db->fetchColumn($countSql, $searchParams);

// 获取成就列表
$sql = "SELECT a.*, g.name as game_name 
        FROM " . DB_PREFIX . "achievements a
        LEFT JOIN " . DB_PREFIX . "games g ON a.game_id = g.id";
$sql .= $searchCondition;
$sql .= " ORDER BY a.id DESC LIMIT ?, ?";

$achievements = $db->fetchAll($sql, array_merge($searchParams, [$offset, $perPage]));

// 获取所有游戏用于筛选
$games = $db->fetchAll("SELECT id, name FROM " . DB_PREFIX . "games WHERE status = 'active' ORDER BY name");

// 计算总页数
$totalPages = ceil($totalAchievements / $perPage);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-trophy"></i> 成就管理</h1>
    <a href="achievement_edit.php" class="btn btn-primary">
        <i class="bi bi-plus-circle"></i> 添加成就
    </a>
</div>

<!-- 搜索框 -->
<div class="card mb-4">
    <div class="card-body">
        <form action="achievements.php" method="get" class="row g-3">
            <div class="col-md-4">
                <div class="input-group">
                    <input type="text" class="form-control" id="search" name="search" 
                           placeholder="搜索成就名称或描述" value="<?php echo htmlspecialchars($search); ?>">
                    <button class="btn btn-primary" type="submit">
                        <i class="bi bi-search"></i> 搜索
                    </button>
                </div>
            </div>
            
            <div class="col-md-3">
                <select class="form-select" id="game_id" name="game_id">
                    <option value="0">全部游戏</option>
                    <?php foreach ($games as $game): ?>
                        <option value="<?php echo $game['id']; ?>" <?php echo $gameId == $game['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($game['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-3">
                <select class="form-select" id="status_filter" name="status_filter">
                    <option value="">全部状态</option>
                    <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>活跃</option>
                    <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>禁用</option>
                </select>
            </div>
            
            <div class="col-md-2">
                <?php if (!empty($search) || $gameId > 0 || !empty($status)): ?>
                    <a href="achievements.php" class="btn btn-outline-secondary w-100">清除筛选</a>
                <?php else: ?>
                    <button type="submit" class="btn btn-outline-primary w-100">应用筛选</button>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- 成就列表 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-table me-1"></i> 成就列表
        <span class="badge bg-info ms-2"><?php echo $totalAchievements; ?> 个成就</span>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th width="60">ID</th>
                        <th width="60">图标</th>
                        <th>名称</th>
                        <th>游戏</th>
                        <th>解锁条件</th>
                        <th>点数</th>
                        <th>状态</th>
                        <th>解锁人数</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($achievements)): ?>
                        <?php foreach ($achievements as $achievement): ?>
                        <tr>
                            <td><?php echo $achievement['id']; ?></td>
                            <td class="text-center">
                                <?php if (!empty($achievement['icon'])): ?>
                                    <img src="<?php echo htmlspecialchars($achievement['icon']); ?>" alt="成就图标" class="img-thumbnail" style="max-width: 40px; max-height: 40px;">
                                <?php else: ?>
                                    <i class="bi bi-trophy fs-3"></i>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="achievement_detail.php?id=<?php echo $achievement['id']; ?>">
                                    <?php echo htmlspecialchars($achievement['name']); ?>
                                </a>
                                <div class="small text-muted">
                                    <?php echo substr(htmlspecialchars($achievement['description']), 0, 50) . (strlen($achievement['description']) > 50 ? '...' : ''); ?>
                                </div>
                            </td>
                            <td>
                                <?php if ($achievement['game_id']): ?>
                                    <a href="game_detail.php?id=<?php echo $achievement['game_id']; ?>">
                                        <?php echo htmlspecialchars($achievement['game_name']); ?>
                                    </a>
                                <?php else: ?>
                                    <span class="text-muted">全局成就</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($achievement['criteria']); ?></td>
                            <td class="text-center"><?php echo $achievement['points']; ?></td>
                            <td>
                                <?php if ($achievement['status'] == 'active'): ?>
                                    <span class="badge bg-success">活跃</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">禁用</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <?php
                                // 获取成就解锁人数
                                $unlocksCount = $db->fetchColumn(
                                    "SELECT COUNT(*) FROM " . DB_PREFIX . "user_achievements WHERE achievement_id = ?",
                                    [$achievement['id']]
                                );
                                echo number_format($unlocksCount);
                                ?>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="achievement_detail.php?id=<?php echo $achievement['id']; ?>" class="btn btn-info" title="查看详情">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <a href="achievement_edit.php?id=<?php echo $achievement['id']; ?>" class="btn btn-primary" title="编辑">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <?php if ($achievement['status'] == 'active'): ?>
                                        <a href="achievements.php?achievement_id=<?php echo $achievement['id']; ?>&status=inactive" 
                                           class="btn btn-warning" title="禁用"
                                           onclick="return confirm('确定要禁用此成就吗？')">
                                            <i class="bi bi-slash-circle"></i>
                                        </a>
                                    <?php else: ?>
                                        <a href="achievements.php?achievement_id=<?php echo $achievement['id']; ?>&status=active" 
                                           class="btn btn-success" title="激活">
                                            <i class="bi bi-check-circle"></i>
                                        </a>
                                    <?php endif; ?>
                                    <a href="achievements.php?delete=<?php echo $achievement['id']; ?>" 
                                       class="btn btn-danger" title="删除"
                                       onclick="return confirm('确定要删除此成就吗？此操作不可撤销，所有用户的成就记录将被删除。')">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="text-center">没有找到符合条件的成就</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 分页 -->
    <?php if ($totalPages > 1): ?>
    <div class="card-footer">
        <nav>
            <ul class="pagination justify-content-center mb-0">
                <?php
                // 分页导航
                renderPagination($page, $totalPages, 'achievements.php', [
                    'search' => $search,
                    'game_id' => $gameId,
                    'status_filter' => $status
                ]);
                ?>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

<?php
require_once 'includes/footer.php';
?> 